<?php
namespace app\api\controller;

use app\api\model\ApplyModel;
use app\index\model\VisitorModel;
use app\api\model\FriendsModel;
use think\Db;

class Friends extends Base {
	/**
	 * [获取好友列表]
	 */
	public function getFriendsList() {
		$visitorModel = new VisitorModel();
		$friendsModel = new FriendsModel();
		$data['friend_cout'] = $friendsModel::where("belong_to",$this->params['user_id'])->count();
		$letterIndex =  $friendsModel::where("belong_to",$this->params['user_id'])
			->field("count(*) as total")->group("letter_index")->column(["letter_index"]);
		$data['friend_list'] = [];
		foreach($letterIndex as $v){
			$item = $friendsModel::where([
				"belong_to" => $this->params['user_id'],
				"letter_index" => $v
			])->select()->toArray();
			if(!empty($item)){
				$arr = [];
				foreach($item as $va){
					$visitor = $visitorModel::where('id',$va['visitor_id'])->field("nick_name,id,head")->find()->toArray();
					if($va['remark_name']){
						$visitor['nick_name'] = $va['remark_name']."（".$visitor['nick_name']."）";
					}
					$arr[] = [
						'name' => $visitor['nick_name'],
						'to' => $visitor['id'],
						'head' => $_SERVER['REQUEST_SCHEME']."://".$_SERVER['SERVER_NAME'].$visitor['head'],
					];
				}
				$data['friend_list'][] = [
					"initial" => $v,
					"item" => $arr
				];
			}
		}
		return json(['code'=>1,'msg'=>"ok",'data'=>$data]);
	}

	/**
	 * [获取好友详情]
	 */
	public function getFriendsInfoById() {
		$visitorModel = new VisitorModel();
		$friendsModel = new FriendsModel();
		$data = $visitorModel::where('id',$this->params['friend_id'])->field("user_name,email")->find()->toArray();
		$data['remark_name'] = $friendsModel::where([
			"belong_to" => $this->params['belong_to'],
			"visitor_id" => $this->params['friend_id'],
		])->value("remark_name");
		return json(["code"=>1,"msg"=>"ok","data"=>$data]);
	}

	/**
	 * [获取好友申请列表]
	 */
	public function getApplyList() {
		$applyModel = new ApplyModel();
		$data = $applyModel::alias("apply")
			->join('home_visitor visitor', 'apply.from_id = visitor.id')
			->where('apply.to_id',$this->params['user_id'])
			->field([
				'apply.id as apply_id,apply.remark',
				'visitor.id as visitor_id,visitor.nick_name,visitor.head'
			])->select()->toArray();
		foreach($data as &$v){
			$v['head'] = $_SERVER['REQUEST_SCHEME']."://".$_SERVER['SERVER_NAME'].$v['head'];
		}
		return json(['code'=>1,'msg'=>"ok",'data'=>$data]);
	}

	/**
	 * [好友申请]
	 */
	public function friendApply() {
		if($this->params['from_id'] == $this->params['to_id']) {
			return json(['code'=>0,'msg'=>'不能自己添加自己哦~','data'=>""]);
		}
		$applyModel = new ApplyModel();
		$friendsModel = new FriendsModel();
		$visitorModel = new VisitorModel();
		$count = $friendsModel::where([
			"belong_to" => $this->params['from_id'],
			"visitor_id" => $this->params['to_id']
		])->count();
		if($count != 0){
			return json(['code'=>0,'msg'=>'你们已经是好友了，请勿重复添加','data'=>""]);
		}
		$count = $applyModel::where([
			"from_id" => $this->params['from_id'],
			"to_id" => $this->params['to_id']
		])->count();
		if($count >= 3){
			return json(['code'=>0,'msg'=>'申请已经提交，请勿重复提交','data'=>'']);
		}
		$from_visitor = $visitorModel::where("id",$this->params['from_id'])
				->field("id,nick_name,user_name,head")->find()->toArray();
		$applyModel::startTrans();
		try {
			// 插入数据库
			$applyModel::insert($this->params);
			// socket推送
			$push_msg = $from_visitor['nick_name']."请求添加您为好友";
			$this->socket_push([$this->params['to_id']],$push_msg,$this->params['from_id'],$from_visitor,"applyFriend");
			// 个推推送
			// code ...
			$applyModel::commit();
			return json(['code'=>1,'msg'=>'申请已发出','data'=>'']);
		} catch (\Exception $e) {
			$applyModel::rollback();
			return json(['code'=>0,'msg'=>'好友申请发送失败：'.$e->getMessage(),'data'=>'']);
		}
	}

	/**
	 * [同意好友申请]
	 */
	public function agreeApply() {
		DB::startTrans();
		try {
			// 删除申请
			DB::name("visitor_friends_apply")->where([
				"from_id" => $this->params['from_id'],
				"to_id" => $this->params['to_id']
			])->delete();
			// 添加双方好友
			$checkCount = DB::name("visitor_friends")->where([
				"belong_to" => $this->params['from_id'],
				"visitor_id" => $this->params['to_id']
			])->count();
			if($checkCount != 0){
				$checkCount = DB::name("visitor_friends")->where([
					"belong_to" => $this->params['to_id'],
					"visitor_id" => $this->params['from_id']
				])->count();
				if($checkCount != 0){
					return json(['code'=>0,'msg'=>'你们已经是好友了~',"data"=>""]);
				}
			}else{
				$data_from = [
					"belong_to" => $this->params['from_id'],
					"visitor_id" => $this->params['to_id'],
					"letter_index" => getFirstChar(DB::name("home_visitor")->where("id",$this->params['to_id'])->value("nick_name"))
				];
				$data_to = [
					"belong_to" => $this->params['to_id'],
					"visitor_id" => $this->params['from_id'],
					"letter_index" => getFirstChar(DB::name("home_visitor")->where("id",$this->params['from_id'])->value("nick_name"))
				];
				DB::name("visitor_friends")->insert($data_from);
				DB::name("visitor_friends")->insert($data_to);
			}
			// 创立聊天室
			$checkCount = DB::name("visitor_chatroom")->where([
				"visitor_ids" => "|".$this->params['to_id']."|,|".$this->params['from_id']."|"
			])->whereOr([
				"visitor_ids" => "|".$this->params['from_id']."|,|".$this->params['to_id']."|"
			])->find();
			if(empty($checkCount)){
				$data_chatroom = [
					"visitor_ids" => "|".$this->params['to_id']."|,|".$this->params['from_id']."|",
					"chat_name" => "ChatRoom",
					"ct_path" => "/upload/chatfile/0.chatfile",
					"last_msg" => "我们已经是好友了，开始聊天吧",
					"last_vid" => $this->params['to_id']
				];
				$chatRoomId = DB::name("visitor_chatroom")->insertGetId($data_chatroom);
				$ct_path = creatChatFile($chatRoomId);
				DB::name("visitor_chatroom")->where("id",$chatRoomId)->update(["ct_path" => $ct_path]);
			}else{
				$chatRoomId = $checkCount['id'];
			}
			// socket:用 to_id 给 from_id 发送消息 "我们已经是好友了，开始聊天吧";
			$this->socketSendMsg($chatRoomId,"我们已经是好友了，开始聊天吧",$this->params['to_id'],"agreeApplyFriend");
			// 个推推送
			// code ...
			DB::commit();
			return json(['code'=>1,'msg'=>'已同意','data'=>'']);
		} catch (\Exception $e) {
			DB::rollback();
			return json(['code'=>0,'msg'=>'操作失败，请稍后：'.$e->getMessage(),'data'=>'']);
		}
	}

	/**
	 * [拒绝好友申请]
	 */
	public function disagreeApply() {
		$applyModel = new ApplyModel();
		$applyModel::startTrans();
		try {
			$applyModel::where([
				"from_id" => $this->params['from_id'],
				"to_id" => $this->params['to_id'],
			])->delete();
			$applyModel::commit();
			return json(['code'=>1,'msg'=>'已拒绝','data'=>'']);
		} catch (\Exception $e) {
			$applyModel::rollback();
			return json(['code'=>0,'msg'=>'操作失败，请稍后：'.$e->getMessage(),'data'=>'']);
		}
	}

	/**
	 * [修改好友备注]
	 */
	public function editRemarkName() {
		if(!$this->params['belong_to'] || !$this->params['friend_id'] || !$this->params['remark_name']){
			return json(['code'=>0,'msg'=>'参数错误','data'=>'']);
		}
		if(mb_strlen($this->params['remark_name']) > 16 || mb_strlen($this->params['remark_name']) < 1 ){
			return json(['code'=>0,'msg'=>'备注名称的字符串长度为1~16','data'=>'']);
		}
		$friendsModel = new FriendsModel();
		$friendsModel::startTrans();
		try {
			$friendsModel::where([
				"belong_to" => $this->params['belong_to'],
				"visitor_id" => $this->params['friend_id'],
			])->update([
				"remark_name" => $this->params['remark_name'],
				"letter_index" => getFirstChar($this->params['remark_name'])
			]);
			$friendsModel::commit();
			return json(['code'=>1,'msg'=>'修改成功','data'=>'']);
		} catch (\Exception $e) {
			$friendsModel::rollback();
			return json(['code'=>0,'msg'=>'修改失败，请稍后：'.$e->getMessage(),'data'=>'']);
		}

	}

	/**
	 * [删除好友]
	 */
	public function delFriend() {
		if(!$this->params['visitor_id_0'] || !$this->params['visitor_id_1']){
			return json(['code'=>0,'msg'=>'参数错误','data'=>'']);
		}
		DB::startTrans();
		try {
			// 删除互相好友表
			DB::name("visitor_friends")->where([
				'belong_to' => $this->params['visitor_id_0'],
				'visitor_id' => $this->params['visitor_id_1']
			])->delete();
			DB::name("visitor_friends")->where([
				'belong_to' => $this->params['visitor_id_1'],
				'visitor_id' => $this->params['visitor_id_0']
			])->delete();
			// 删除聊天记录表和聊天文件
			$chatRoom = DB::name("visitor_chatroom")->where([
				"visitor_ids" => "|".$this->params['visitor_id_0']."|,|".$this->params['visitor_id_1']."|"
			])->whereOr([
				"visitor_ids" => "|".$this->params['visitor_id_1']."|,|".$this->params['visitor_id_0']."|"
			])->find();
			if(!empty($chatRoom)){
				$ct_path = APP_PATH."../public".$chatRoom['ct_path'];
				$ct_path = iconv("UTF-8", "GBK", $ct_path);
				if(file_exists($ct_path)){
					@unlink($ct_path);
				}
				DB::name("visitor_chatroom")->where("id",$chatRoom['id'])->delete();
			}
			DB::commit();
			return json(['code'=>1,'msg'=>'删除成功','data'=>'']);
		} catch (\Exception $e) {
			DB::rollback();
			return json(['code'=>0,'msg'=>'删除失败，请稍后：'.$e->getMessage(),'data'=>'']);
		}
	}

	/**
	 * [搜索添加好友]
	 */
	public function searchFriend() {
		if(!$this->params['searchText']){
			return json(['code'=>0,'msg'=>"请输入搜索内容",'data'=>""]);
		}
		$visitorModel = new VisitorModel();
		$pre_fix = $_SERVER['REQUEST_SCHEME']."://".$_SERVER['SERVER_NAME'];
		$where = [
			'user_name' => ['like',"%".$this->params['searchText']."%"],
			'email' => ['like',"%".$this->params['searchText']."%"],
		];
		$data = $visitorModel::whereOr($where)
			->field(["id,user_name,nick_name,email","concat('".$pre_fix."',head)" => "user_head"])
			->order("id asc")->limit(0,20)->select()->toArray();
		return json(['code'=>1,'msg'=>"ok",'data'=>$data]);
	}
}
